import { getUserInfoService } from '@/apis/user'
import { useUserStore } from '@/stores'
import type { Router } from 'vue-router'

//白名单
const whiteList = ['/login', '/401', '/404']

export const setGuard = (router: Router) => {
  router.beforeEach(async to => {
    const userStore = useUserStore()
    // 如果用户已经登录，则直接跳转
    if (userStore.token) {
      if(!userStore.userInfo || !userStore.userInfo.id){
        const res = await getUserInfoService()
        userStore.setUserInfo(res.data.data)
      }
      // 如果是登录页，直接跳转到首页
      if (to.path === '/login') {
        return '/'
      }
      return true
    } else {
      // 如果是白名单，直接跳转
      if (whiteList.includes(to.path)) {
        return true
      }
      return '/login'
    }
  })
}
